<template>
  <div class="app-container dashboard">
    <!-- 顶部控制栏 -->
    <div class="dashboard-header">
      <div class="header-left">
        <div class="welcome-info">
          <h2>欢迎回来，{{ userName }}</h2>
          <p>{{ currentTime }}</p>
        </div>
      </div>
      <div class="header-right">
        <div class="weather-info" v-if="weatherData">
          <i class="el-icon-sunny"></i>
          <span>{{ weatherData.city }} {{ weatherData.weather }} {{ weatherData.temperature }}°C</span>
        </div>
        <div class="control-buttons">
          <el-button-group>
            <el-button 
              :type="timeRange === 'today' ? 'primary' : ''" 
              size="small" 
              @click="changeTimeRange('today')"
            >今日</el-button>
            <el-button 
              :type="timeRange === 'week' ? 'primary' : ''" 
              size="small" 
              @click="changeTimeRange('week')"
            >本周</el-button>
            <el-button 
              :type="timeRange === 'month' ? 'primary' : ''" 
              size="small" 
              @click="changeTimeRange('month')"
            >本月</el-button>
          </el-button-group>
          <el-switch
            v-model="autoRefresh"
            active-text="实时更新"
            inactive-text="手动刷新"
            @change="handleAutoRefreshChange"
            style="margin-left: 15px;"
          ></el-switch>
        </div>
      </div>
    </div>

    <!-- 统计卡片区域 -->
    <el-row :gutter="20" class="statistics-row">
      <el-col :xs="12" :sm="8" :md="6" :lg="4" :xl="4" v-for="card in statisticsCards" :key="card.key">
        <statistics-card
          :title="card.title"
          :value="card.value"
          :icon="card.icon"
          :icon-color="card.iconColor"
          :trend="card.trend"
          :trend-text="card.trendText"
          @click.native="handleCardClick(card.key)"
        />
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20">
      <!-- 模型训练状态分布 -->
      <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8">
        <chart-card
          title="模型训练状态分布"
          :height="300"
          :options="modelStatusChartOptions"
        />
      </el-col>

      <!-- 各车间光谱数据量 -->
      <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8">
        <chart-card
          title="各车间光谱数据量"
          :height="300"
          :options="workshopSpectrumChartOptions"
        />
      </el-col>

      <!-- 仪器状态统计 -->
      <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8">
        <chart-card
          title="仪器状态统计"
          :height="300"
          :options="instrumentStatusChartOptions"
        />
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <!-- 成分检测分布 -->
      <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
        <chart-card
          title="成分检测分布"
          :height="350"
          :options="constituentDistributionChartOptions"
        />
      </el-col>

      <!-- 最近光谱采集趋势 -->
      <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
        <chart-card
          title="最近光谱采集趋势"
          :height="350"
          :options="recentSpectrumTrendChartOptions"
        />
      </el-col>
    </el-row>

    <!-- 管理员专属区域 -->
    <el-row :gutter="20" v-if="isAdmin">
      <!-- 系统运行状态 -->
      <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
        <chart-card
          title="系统运行状态监控"
          :height="250"
          :options="systemStatusChartOptions"
        >
          <template #actions>
            <el-button size="mini" type="text" @click="viewSystemLogs">查看日志</el-button>
          </template>
        </chart-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import StatisticsCard from '@/components/Dashboard/StatisticsCard.vue'
import ChartCard from '@/components/Dashboard/ChartCard.vue'
import { mapGetters } from 'vuex'

export default {
  name: "Index",
  components: {
    StatisticsCard,
    ChartCard
  },
  data() {
    return {
      // 版本号
      version: "3.8.9",
      // 时间范围
      timeRange: 'today',
      // 自动刷新
      autoRefresh: false,
      refreshTimer: null,
      // 当前时间
      currentTime: '',
      timeTimer: null,
      // 天气数据
      weatherData: {
        city: '北京',
        weather: '晴',
        temperature: 22
      },
      // 统计卡片数据
      statisticsCards: [
        {
          key: 'totalModels',
          title: '模型总数',
          value: 25,
          icon: 'el-icon-cpu',
          iconColor: '#409EFF',
          trend: 'up',
          trendText: '较昨日 +5'
        },
        {
          key: 'trainingModels',
          title: '训练中模型',
          value: 3,
          icon: 'el-icon-loading',
          iconColor: '#E6A23C',
          trend: 'stable',
          trendText: '无变化'
        },
        {
          key: 'completedModels',
          title: '已完成模型',
          value: 20,
          icon: 'el-icon-check',
          iconColor: '#67C23A',
          trend: 'up',
          trendText: '较昨日 +3'
        },
        {
          key: 'spectrumSamples',
          title: '光谱样本总数',
          value: 2580,
          icon: 'el-icon-data-line',
          iconColor: '#909399',
          trend: 'up',
          trendText: '较昨日 +12'
        },
        {
          key: 'totalInstruments',
          title: '仪器总数',
          value: 12,
          icon: 'el-icon-monitor',
          iconColor: '#F56C6C',
          trend: 'stable',
          trendText: '无变化'
        },
        {
          key: 'onlineInstruments',
          title: '在线仪器',
          value: 10,
          icon: 'el-icon-connection',
          iconColor: '#67C23A',
          trend: 'up',
          trendText: '较昨日 +1'
        }
      ],
      // 图表配置
      modelStatusChartOptions: {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 10,
          data: ['训练中', '已完成', '失败', '待训练']
        },
        series: [
          {
            name: '模型状态',
            type: 'pie',
            radius: ['40%', '70%'],
            center: ['60%', '50%'],
            data: [
              { value: 3, name: '训练中' },
              { value: 20, name: '已完成' },
              { value: 1, name: '失败' },
              { value: 5, name: '待训练' }
            ],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      },
      workshopSpectrumChartOptions: {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: ['DFB车间', '造粒车间', '环保车间']
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '光谱数据量',
            type: 'bar',
            data: [1200, 800, 580],
            itemStyle: {
              color: '#409EFF'
            }
          }
        ]
      },
      instrumentStatusChartOptions: {
        tooltip: {
          trigger: 'item'
        },
        series: [
          {
            name: '仪器状态',
            type: 'pie',
            radius: '70%',
            data: [
              { value: 10, name: '在线', itemStyle: { color: '#67C23A' } },
              { value: 1, name: '离线', itemStyle: { color: '#F56C6C' } },
              { value: 1, name: '维护中', itemStyle: { color: '#E6A23C' } }
            ],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      },
      constituentDistributionChartOptions: {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: ['水分', '灰分', '挥发分', '固定碳', '硫分']
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '检测次数',
            type: 'bar',
            data: [450, 380, 320, 280, 150],
            itemStyle: {
              color: '#409EFF'
            }
          }
        ]
      },
      recentSpectrumTrendChartOptions: {
        tooltip: {
          trigger: 'axis'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: ['1日', '2日', '3日', '4日', '5日', '6日', '7日']
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '采集数量',
            type: 'line',
            stack: 'Total',
            data: [120, 132, 101, 134, 90, 230, 210],
            smooth: true,
            itemStyle: {
              color: '#409EFF'
            },
            areaStyle: {
              color: 'rgba(64, 158, 255, 0.2)'
            }
          }
        ]
      },
      systemStatusChartOptions: {
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['CPU使用率', '内存使用率', '磁盘使用率']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: ['00:00', '04:00', '08:00', '12:00', '16:00', '20:00', '24:00']
        },
        yAxis: {
          type: 'value',
          max: 100,
          axisLabel: {
            formatter: '{value}%'
          }
        },
        series: [
          {
            name: 'CPU使用率',
            type: 'line',
            data: [20, 25, 30, 45, 55, 40, 35],
            smooth: true,
            itemStyle: { color: '#409EFF' }
          },
          {
            name: '内存使用率',
            type: 'line',
            data: [30, 35, 40, 50, 60, 55, 45],
            smooth: true,
            itemStyle: { color: '#67C23A' }
          },
          {
            name: '磁盘使用率',
            type: 'line',
            data: [65, 66, 67, 68, 69, 70, 71],
            smooth: true,
            itemStyle: { color: '#E6A23C' }
          }
        ]
      }
    };
  },
  computed: {
    ...mapGetters(['name', 'roles']),
    userName() {
      return this.name || '用户'
    },
    isAdmin() {
      // 容错处理：如果 roles 为空或未定义，默认为普通用户
      if (!this.roles || !Array.isArray(this.roles)) {
        return false
      }
      return this.roles.some(role => role === 'admin' || role === 'ROLE_ADMIN')
    }
  },
  mounted() {
    this.initCurrentTime()
  },
  beforeDestroy() {
    if (this.refreshTimer) {
      clearInterval(this.refreshTimer)
    }
    if (this.timeTimer) {
      clearInterval(this.timeTimer)
    }
  },
  methods: {
    // 初始化当前时间
    initCurrentTime() {
      this.updateCurrentTime()
      this.timeTimer = setInterval(this.updateCurrentTime, 1000)
    },
    
    // 更新当前时间
    updateCurrentTime() {
      const now = new Date()
      const options = {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
        weekday: 'long',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      }
      this.currentTime = now.toLocaleDateString('zh-CN', options)
    },

    // 时间范围改变
    changeTimeRange(range) {
      this.timeRange = range
      // 这里可以根据时间范围更新数据，暂时不做处理避免API错误
    },

    // 自动刷新开关
    handleAutoRefreshChange(value) {
      if (value) {
        this.refreshTimer = setInterval(() => {
          // 这里可以刷新数据，暂时不做处理避免API错误
          console.log('自动刷新数据')
        }, 30000) // 30秒刷新一次
      } else {
        if (this.refreshTimer) {
          clearInterval(this.refreshTimer)
          this.refreshTimer = null
        }
      }
    },

    // 卡片点击事件
    handleCardClick(key) {
      // 根据卡片类型跳转到相应页面
      const routeMap = {
        totalModels: '/model/data',
        trainingModels: '/model/data?status=training',
        completedModels: '/model/data?status=completed',
        spectrumSamples: '/spectrum',
        totalInstruments: '/instrument/data',
        onlineInstruments: '/instrument/data?status=online'
      }
      
      if (routeMap[key]) {
        this.$router.push(routeMap[key])
      }
    },

    // 查看系统日志
    viewSystemLogs() {
      this.$router.push('/monitor/operlog')
    }
  }
};
</script>

<style scoped lang="scss">
.dashboard {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);

  .dashboard-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding: 20px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

    .header-left {
      .welcome-info {
        h2 {
          margin: 0 0 5px 0;
          font-size: 24px;
          font-weight: 500;
          color: #333;
        }

        p {
          margin: 0;
          color: #666;
          font-size: 14px;
        }
      }
    }

    .header-right {
      display: flex;
      align-items: center;
      gap: 20px;

      .weather-info {
        display: flex;
        align-items: center;
        gap: 8px;
        color: #666;
        font-size: 14px;

        i {
          color: #f39c12;
        }
      }

      .control-buttons {
        display: flex;
        align-items: center;
      }
    }
  }

  .statistics-row {
    margin-bottom: 20px;
  }

  // 响应式设计
  @media (max-width: 768px) {
    padding: 10px;

    .dashboard-header {
      flex-direction: column;
      gap: 15px;
      text-align: center;

      .header-right {
        flex-direction: column;
        gap: 10px;
      }
    }
  }

  @media (max-width: 576px) {
    .statistics-row {
      .el-col {
        margin-bottom: 10px;
      }
    }
  }
}

// 全局图表样式
:deep(.chart-card) {
  .el-card__header {
    border-bottom: 1px solid #ebeef5;
    padding: 15px 20px;
  }

  .el-card__body {
    padding: 20px;
  }
}

// 统计卡片动画
.statistics-card {
  transition: all 0.3s ease;
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  }
}
</style>